package cn.wolfcode.web.controller;

import cn.wolfcode.ann.RequiredPermission;
import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequiredPermission(name="员工页面",expression = "employee:list")

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        return "employee/list";
    }
    @RequiredPermission(name="新增/编辑",expression = "employee:saveOrUpdate")
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        //用于回显右边角色
        List<Role> roles = employeeService.queryRoleNameByEmpId(id);
        model.addAttribute("roless", roles);
        //查询所有角色ID
        model.addAttribute("role",roleService.selectAll());
        if (id != null) {
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
        }
        return "employee/input";
    }
    @RequiredPermission(name="新增/编辑",expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Employee employee,Long[] ids){
        if (employee.getId()==null){
            employeeService.save(employee,ids);
        }else {
            employeeService.update(employee,ids);
        }
        return "redirect:/employee/list";
    }
    @RequiredPermission(name="员工删除",expression = "employee:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id!=null){
            employeeService.delete(id);
        }
        return "redirect:/employee/list";
    }
}